#!F:/Python/python.exe
#coding=utf-8

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import cjson
import skyservice, skyServantLocator
#from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler, CGIXMLRPCRequestHandler
#from SocketServer import ThreadingMixIn
import types,traceback, sys, gzip, cStringIO, time

#print cjson.decode('{"Name":"logIn","Params":[name,password,...]}')
#print cjson.encode({"Result":hex(20)})

def compressData(str2Compress):
    """compress to fileObj.
    
        str2Compress: 
            [str2Compress] is a string value to be compressed into cStringIO.StringIO
    """
    fileObj = cStringIO.StringIO()
    g = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=fileObj)
    g.write(str2Compress) #write string and compress
    g.flush() # refresh the buffer which is in gcontent
    g.close()
    return fileObj.getvalue()
#    return fileObj

locator = skyServantLocator.SkyEvictor()
class JSONRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        #step 1:read data from client and decode it
        print self.headers
        s = self.rfile.read(int(self.headers['Content-Length']))
        rpcParams = cjson.decode(s)
        print rpcParams
        ret = None
        #step 2:dispath to handling function by function names and parameters
        try:
            ret = getattr(self, 'service_'+rpcParams['Name'])(*rpcParams['Params'])
        except Exception:
        #step 2.1：if has Exception raise , get Errorcode and info to client
            traceback.print_exc(file=sys.stdout)
            ret = cjson.encode({"Exception":{"Code":20001,"Msg":"error!"}})
        
        
    def do_POST(self):
        #step 1:read data from client and decode it
        print self.headers
        s = self.rfile.read(int(self.headers['Content-Length']))      
        rpcParams = cjson.decode(s[2:])
        print rpcParams
        ret = None
        #step 2:dispath to handling function by function names and parameters
        try:
            ret = getattr(self, 'service_'+rpcParams['Name'])(*rpcParams['Params'])
        except Exception:
        #step 2.1：if has Exception raise , get Errorcode and info to client
            traceback.print_exc(file=sys.stdout)
            ret = cjson.encode({"Exception":{"Code":20001,"Msg":"error!"}})
        #step 3:remove withspace, which can readuce size
        print "before replace withespace:",ret, len(ret)
        retCmp = compressData(ret.replace(" ", ""))
        print "end replace withespace:",ret, len(ret)
        self.send_response( 200 )        
        self.send_header( 'Content-Length', len(retCmp) )
        self.end_headers()
        self.wfile.write( retCmp )
        print '\n', 'time is:' , time.time()
        
    def service_test(self, intVar):
        ret = cjson.encode({"Result":hex(intVar)})
        print ret
#        self.send_header()

        
#    def service_find(self, context, pageNum, pageSize, type):
#        scene = ContactScene("testScene", 1, 1, 1, 1, 1, 1, 1, 1, 11)
#        scene1 = ContactScene("testScene1", 2, 1, 1, 1, 1, 1, 1, 1, 11)
#        scene2 = ContactScene("testScene2", 3, 1, 1, 1, 1, 1, 1, 1, 11)
#        scene3 = ContactScene("testScene3", 4, 1, 1, 1, 1, 1, 1, 1, 11)
#        scene4 = ContactScene("testScene4", 5, 1, 1, 1, 1, 1, 1, 1, 11)
#        scene5 = ContactScene("testScene5", 6, 1, 1, 1, 1, 1, 1, 1, 11)
##        id='', nameSeq=None, phoneSeq=None, emailSeq=None, addrSeq=None, urlSeq=None, photoSeq=None, remarkSeq=None, imSeq=None, sceneSeq=None, defaultScene=0, lastModified=0
#        item = ContactItem("Bruce"        
#                        , ["xinqi", "bruce.xin", "brucexq", "sean"]
#                        , ["13760113672", "28099947"]
#                        , ["brucexq@tom.com", "bruce.xin@gmail.com"]
#                        , ["nangchang", "shengzheng"]
#                        , ["bruce.xin@blogspot.com"]
#                        , []                        
#                        , ["Good guy!"]
#                        , ["188846893", "bruce.sean@hotmail.com"]
#                        , [scene, scene1, scene2, scene3, scene4, scene5]
#                        , 1
#                        , 1111)
#        ret = cjson.encode({"result":{"totalSize":1, "items":[item.toList(),item.toList(),item.toList(),item.toList(),item.toList()]}})
#        print len(ret)
#        self.send_response( 200 )        
#        self.send_header( 'Content-Length', len(ret) )
#        self.end_headers()
#        self.wfile.write( ret )
        
    def service_logIn(self, id, pwd, deviceInfo):
#        print self.client_address
        secManager = skyservice.SkySecManager()
        if secManager.logIn(id, pwd):
            return cjson.encode({"Result":str(locator.login(id, deviceInfo))})
        
    def service_signIn(self, info):  
        secManager = skyservice.SkySecManager()
        return secManager.signIn(info)
        
    def service_check(self, id):
        print locals()
        return True

    def service_getCode(self, id):
        print locals()
        return True    

    def service_exit(self, session):    
        print "exit:", locals()  
        return locator.finished(session)       
       
    def service_find(self, session, context, pageNum, pageSize, typeclass):       
        pimManager = locator.locate(session)
        if pimManager != None:
            totalsize, listAll = pimManager.find(context, pageNum, pageSize, typeclass)
        return cjson.encode({"Result":{"totalSize":totalsize, "contactList":listAll}})
       
    def service_delete(self, session, idList):
        pimManager = locator.locate(session)
        if pimManager != None:
            return pimManager.delete(idList)

    def service_add(self, session, contactList):
        pimManager = locator.locate(session)
        if pimManager != None:
            return pimManager.add(contactList)

    def service_update(self, session, contactList):
        pimManager = locator.locate(session)
        if pimManager != None:
            return pimManager.update(contactList)

    def service_size(self, session):
        return 0

    def service_lastModified(self, session):
        pimManager = locator.locate(session)
        if pimManager != None:
            return pimManager.lastModified()
        
    def service_getVOIP(self, session):
        pimManager = locator.locate(session)
        if pimManager != None:
            VOIPList = pimManager.getVOIP()
            return cjson.encode({"Result":VOIPList})

    def service_beginExport(self, accounts):
        pass
    
    def service_endExport(self, accounts):
        pass
    
    def service_export(self, session, contacts):
        pimManager = locator.locate(session)
        if pimManager != None:
            return cjson.encode({"Result":str(pimManager.export(contacts))})

    def service_getInfo(self, session):
        pimManager = locator.locate(session)
        if pimManager != None:
            isucceed,item = pimManager.getInfo()
            return cjson.encode({"Result":item})

    def service_setInfo(self, session, contact):
        pimManager = locator.locate(session)
        if pimManager != None:
            return pimManager.setInfo(contact)
    
    def service_incrementFrequency(self, session, id, sceneIdx, voipName):
        pimManager = locator.locate(session)
        if pimManager != None:
            return pimManager.incrementFrequency(id, sceneIdx, voipName)                      

class ThreadingServer(ThreadingMixIn, HTTPServer):
    pass


serveraddr = ('', 80)
srvr = ThreadingServer(serveraddr, JSONRequestHandler)
srvr.serve_forever()
#end

